package mysql

import (
	"gorm.io/gorm"
	"short-video-dev/videorpc/videorpc"
)

type CollectionInfo struct {
	gorm.Model
	UserId        int `gorm:"type:int(11);not null;comment:'视频ID'"`
	VideoId       int `gorm:"type:int(11);not null;comment:'视频ID'"`
	CollectStatus int `gorm:"type:int(11);not null;default:0;comment:'收藏状态'"`
}

func (i *CollectionInfo) FindCollect(db *gorm.DB, uid, vid int64) error {
	return db.Debug().Where("collection_infos.user_id=? and collection_infos.video_id=?",
		uid, vid).Find(i).Error
}

func (i *CollectionInfo) CollectAdd(db *gorm.DB, id int64) error {
	db.Model(&VideoInfo{}).Where("video_infos.id = ?", id).Update("video_infos.collect_num",
		gorm.Expr("video_infos.collect_num + ?", 1))
	return db.Debug().Create(i).Error
}

func (i *CollectionInfo) CollectDel(db *gorm.DB, uid int64, vid int64) error {
	db.Model(&VideoInfo{}).Where("video_infos.id = ?", vid).Update("video_infos.collect_num",
		gorm.Expr("video_infos.collect_num - ?", 1))
	return db.Debug().Where("user_id=? and video_id=?", uid, vid).Delete(i).Error
}
func CollectList(db *gorm.DB, in *videorpc.CollectListRequest) ([]*videorpc.VideoList, int64) {
	var list []*videorpc.VideoList
	tx := db.Debug().Model(&CollectionInfo{}).Select("video_infos.video_title", "video_infos.cover_link",
		"video_infos.play_num", "user_infos.nike_name", "user_infos.avatar_link as head_image").
		Joins("LEFT JOIN video_infos ON video_infos.id = collection_infos.video_id").
		Joins("left join user_infos on user_infos.id = video_infos.user_id").
		Order("collection_infos.created_at desc")
	var count int64
	tx.Count(&count)
	tx.Scopes(Paginate(int(in.Page), int(in.Size))).Where("collection_infos.user_id = ?", in.UserId).
		Find(&list)
	return list, count
}
